package core.component.interceptor;

import com.distribute.pojo.LoginInfo;
import config.DSConfig;
import core.component.auth.LoginInfoHolder;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;


import java.io.IOException;

import static constant.DSConstants.*;

public class SessionInterceptor implements Interceptor {

    private final DSConfig dsConfig;

    public SessionInterceptor(DSConfig dsConfig) {
        this.dsConfig = dsConfig;
    }

    @NotNull
    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();
        // 如果是登录请求 则跳过 不添加 session id
        if(request.url().uri().getPath().endsWith("/login")){
            return chain.proceed(request);
        }

        LoginInfo login = LoginInfoHolder.getInstance(dsConfig.getUserName());

        if(login.getSessionId() == null){
            return chain.proceed(request);
        }

        Request newRequest = request.newBuilder().header(SESSION_ID, login.getSessionId())
                .header(COOKIE, String.format(COOKIE_INFO, login.getSecurityConfigType(), login.getSessionId(), login.getSessionId()))
                .build();
        return chain.proceed(newRequest);
    }
}
